# define event to event sample method
# 
# Author: guochun
###############################################################################



oneSampling.eToe=function(distanceOBJ,populationData){
	availible=sample(populationData@availible,1)
}


setSampleResult.eToe=function(sampleOBJ,selection,populationData){
	window=owin(c(0,populationData@plotdim[1]),c(0,populationData@plotdim[2]))
	e1=ppp(x=populationData@x[selection],y=populationData@y[selection],window=window,check=F)
	e2=ppp(x=populationData@x[-selection],y=populationData@y[-selection],window=window,check=F)
	nd=nncross(e1,e2)
	sre=data.frame(xfrom=populationData@x[selection],yfrom=populationData@y[selection],xTo=e2[nd[1,2]]$x,yTo=e2[nd[1,2]]$y,d=nd[1,1])
#  browser()
	ns=length(populationData@samples)
	#the formate of distance result is "fromx" "fromy" "Tox"  "Toy" "Distance"
	populationData@samples[[ns+1]]=sre
	return(populationData)
}

#sample all the points at once.
samplingQuick.eToe=function(sampleMethod,populationData){
	#多取20%的点，最后在删除重复点后，若有多余，则可以随机选择需要的点数
	#但这里的问题是，当总点数很少的时候，剩余的点可能就不够了。
	#而且去掉点会产生一个严重的问题，即原本可能的邻体可能已经成了focus而无法再被选中
	#解决这个问题的关键是将endPoints包含所有的点，而且当需要找第一邻体时，k设置成2，或者是统一加1
	spt=round(sampleMethod@time*1.2)
	if(spt>=length(populationData@availible))
		spt=length(populationData@availible)
	
	endPoint=matrix(c(populationData@x,populationData@y),nrow=length(populationData@x),ncol=2)
	findk=sampleMethod@k+1
	
	redo=TRUE
	rdtime=0
	while(redo & rdtime <= sampleMethod@stopLimit){
		rdtime=rdtime+1
		select=sample(populationData@availible,spt)
		#select=sample(1:length(populationData@x),sampleMethod@time)
		
		#win=owin(c(0,populationData@plotdim[1]),c(0,populationData@plotdim[2]))
		#focus = ppp(x=populationData@x[select],y=populationData@y[select],window=win,check=FALSE)
		#endPoint=ppp(x=populationData@x[-select],y=populationData@y[-select], window=win, check=FALSE)
		#nd=nncross(focus,endPoint)
		focus=matrix(c(populationData@x[select],populationData@y[select]),nrow=length(select),ncol=2)
		
		nd=knnx.index(endPoint,focus,k=findk)[,findk]
		
		#redo=length(nd[,2])!=length(unique(nd[,2]))
		sln=length(unique(nd))
		if(sln>=sampleMethod@time){
			redo=FALSE
			temp=table(nd)
			del=match(as.numeric(names(temp)[which(temp>1)]),nd)
			if(length(del)>0){
				nd=nd[-del]
				focus=focus[-del,]
			}
			#print(dim(nd)[1])
			select=sample(1:length(nd),sampleMethod@time)
			nd=nd[select]
			focus=focus[select,]
			#TODO (nd[,2])[-del]
		}else{
			redo=TRUE
			sptmax=round(length(populationData@x)*3/4)
			if(spt <= sptmax)
				spt=sptmax
		}
	}
	
	if(!redo){
		final.d=endPoint[nd,]
		re=sqrt((final.d[,1]-focus[,1])^2+(final.d[,2]-focus[,2])^2)
		return(re)
	}else{
		return(NA)
	}
	
	
	
	#sqrt((A[,1]-B[nd2,1])^2+(A[,2]-B[nd2,2])^2)-nd[,1]
}
